package com.ns.scs.visits.service;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.basic.server.mapper.ServerEntryMapper;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.current.config.SysConst;
import com.ns.core.utils.cache.RedisUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.scs.user.dto.ScsUserPageDto;
import com.ns.scs.visits.entry.Visits;
import com.ns.scs.visits.mapper.VisitsMapper;
import com.ns.scs.visits.vo.VisitsVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 业务用户实现
 *
 * @author lw
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class VisitsServiceImpl extends ServiceImpl<VisitsMapper, Visits> implements IVisitsService {

    private final VisitsMapper mapper;

    private final ServerEntryMapper serverEntryMapper;


    @Override
    public Page<VisitsVO> getList(ScsUserPageDto dto) {
        return mapper.getList(dto, new Page<>(dto.getCurrent(), dto.getSize()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void syncVisits() {
        try {
            List<Object> objects = RedisUtil.forListGet(SysConst.SCS_VISITS);
            if (CollectionUtils.isEmpty(objects)) {
                return;
            }
            List<Visits> visitsList = new ArrayList<>();
            for (Object object : objects) {
                Visits visits = JSON.parseObject(JSON.toJSONString(object), Visits.class);
                visitsList.add(visits);
            }
            mapper.insertOrUpdate(visitsList);
            // 移除缓存=>访问ip及访问对象
            RedisUtil.forSetRemove(SysConst.SCS_VISITS + SymbolsMark.COLON + SymbolsMark.IP);
            RedisUtil.forListRemove(SysConst.SCS_VISITS);
        } catch (Exception e) {
            throw new ResultError("同步访问量信息异常", e);
        }
    }
}
